﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;

namespace BSC_OTC_Management.Code
{
    public class ExportUtility
    {
        public void Export(DataGridView _dgv)
        {
            // Hỏi ng dùng lưu ra loại file gì, lưu ra đâu?
            SaveFileDialog sourceFile = this.SourceFile();
            if (sourceFile.FileName != "")
            {
                switch (sourceFile.FilterIndex)
                {
                    case 1:
                        Export_Excel(_dgv, sourceFile.FileName);
                        break;
                    case 2:
                        Export_Pdf(_dgv, sourceFile.FileName);
                        break;
                    default:
                        break;
                }    
            }
        }

        private void Export_Pdf(DataGridView _dgv, string _sourceFile)
        {
            PdfPTable pdfTable = new PdfPTable(_dgv.ColumnCount);
            pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTable.DefaultCell.BorderWidth = 1;

            //Adding Header row
            foreach (DataGridViewColumn column in _dgv.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                //cell.BackgroundColor = new BaseColor();
                pdfTable.AddCell(cell);
            }

            //Adding DataRow
            foreach (DataGridViewRow row in _dgv.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.Value != null)
                    {
                        pdfTable.AddCell(cell.Value.ToString());
                    }
                    else
                    {
                        pdfTable.AddCell("");
                    }
                }
            }

            using (FileStream stream = new FileStream(_sourceFile, FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                pdfDoc.Add(pdfTable);
                pdfDoc.Close();
                stream.Close();
            }
            MessageBox.Show("Export Successful!");
            System.Diagnostics.Process.Start(_sourceFile);
        }

        private void Export_Excel(DataGridView _dgv, string _sourceFile)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            //xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            // Insert column name vao File Excel
            int stt = 0;
            foreach (System.Windows.Forms.DataGridViewColumn column in _dgv.Columns)
            {
                xlWorkSheet.Cells[1, stt + 1] = column. HeaderText;
                stt++;
            }

            // Insert Tung cell vao file Excel
            for (int i = 0; i <= _dgv.Rows.Count - 1; i++)
            {
                for (int j = 0; j <= _dgv.Columns.Count - 1; j++)
                {
                    xlWorkSheet.Cells[i + 2, j + 1] = _dgv.Rows[i].Cells[j].Value;
                }
            }

            xlWorkBook.SaveAs(_sourceFile, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            MessageBox.Show("Export Successful!");
            System.Diagnostics.Process.Start(_sourceFile);
        }

        // Hỏi nơi lưu file
        private SaveFileDialog SourceFile()
        {
            SaveFileDialog choofdlog = new SaveFileDialog();
            choofdlog.Filter = "Excel (*.xls)|*.xls|Pdf (*.pdf)|*.pdf";
            choofdlog.FilterIndex = 1;
            if (choofdlog.ShowDialog() == DialogResult.OK)
            {
                string sFileName = choofdlog.FileName;
            }
            return choofdlog;
        }


        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
